package com.itheima.reggin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggin.dto.DishDto;
import com.itheima.reggin.entity.Dish;
import com.itheima.reggin.entity.DishFlavor;
import com.itheima.reggin.mapper.DishMapper;
import com.itheima.reggin.service.DishFlavorService;
import com.itheima.reggin.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorService dishFlavorService;

    /**
     * 新增菜品
     * dishDto直接保存到dish表里面
     */

    @Override
    @Transactional(rollbackFor = SQLException.class)  //事务注解控制
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        Long dishId = dishDto.getId();
       flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    /**
     * 根据id 查询菜品的信息和口味信息
     * 先查询dish保存到dishDto里面，然后查询口味表作为list保存到disgDto里面
     * @param id
     */
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public DishDto getByIdWithFlavor(Long id) {

        DishDto dishDto = new DishDto();
        Dish dish = this.getById(id);
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> query = new LambdaQueryWrapper<>();
        query.eq(DishFlavor::getDishId,id);
        List<DishFlavor> listFlavor = dishFlavorService.list(query);
        dishDto.setFlavors(listFlavor);
        return  dishDto;

    }

    /**
     * 修改菜品
     * dish直接保存，口味先删除 在保存
     * @param dishDto
     */
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public void updateWithFlavor(DishDto dishDto) {
        Dish dish = new Dish();
         BeanUtils.copyProperties(dishDto,dish,"flavors");
         this.updateById(dish);
        Long dishid = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> query = new LambdaQueryWrapper<>();
        query.eq(DishFlavor::getDishId,dishid);
        dishFlavorService.remove(query);
        List<DishFlavor> flavors = dishDto.getFlavors();
        dishFlavorService.saveBatch(flavors);

    }
}
